const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}


const newRequest = (url, method, data, isJsonBody) => {
  return new Promise(function(resolve, reject) {
    const prefix = url.startsWith('http') ? '' : getApp().globalData.baseUrl;
    if (url != '/upload/user.php') {
      wx.showLoading({
        title: '加载中',
      })
    }

    wx.request({
      url: prefix + url,
      header: {
        // "Content-Type": "application/json",
        "Content-Type": isJsonBody ? 'application/json' : "application/x-www-form-urlencoded",
        "Authorization": "Bearer " + getApp().globalData.token,
      },
      method: method,
      // data: method=='GET' ? data : JSON.stringify(data),
      data: isJsonBody ? JSON.stringify(data) : data,
      success: function(res) {
        wx.hideLoading()
        if (res.statusCode == 200) {
          if (res.header.Authorization) {
            getApp().globalData.token = res.header.Authorization
          }
          resolve(res)
        } else {
          reject(res)
        }
      },
      fail: function(res) {
        wx.hideLoading()
        reject(res)
      },
      complete: function(res) {
        // console.log('request finished ', res)
      }
    })
  })

}

newRequest.get = (url, data) => newRequest(url, 'GET', data)
newRequest.post = (url, data, isJsonBody) => newRequest(url, 'POST', data, isJsonBody)


const listeners = {}
const events = []

const on = (event, callback) => {
  console.log('监听事件', event)
  for (let i = 0; i < events.length; i++) {
    if (events[i].event == event) {
      console.log('found unhandled event', events[i])
      callback(events[i].data)
      events.splice(i, 1)
    }
  }
  listeners[event] = callback
}

const emit = (event, data) => {
  // console.log('触发事件', event, data)
  const callback = listeners[event]
  if (callback) {
    callback(data)
  } else {
    events.push({
      event,
      data
    })
    // console.log('没有发现监听器，事件先进队列', event, data)
  }
}

// 连续点击两次的问题 使用道具--3秒
const buttonClickedLong = (self) => {
  self.setData({
    buttonClickedLong: true
  })
  setTimeout(function() {
    self.setData({
      buttonClickedLong: false
    })
  }, 3000)
}

// 连续点击两次的问题 使用道具
const buttonClicked = (self) => {
  self.setData({
    buttonClicked: true
  })
  setTimeout(function() {
    self.setData({
      buttonClicked: false
    })
  }, 1000)
}

const get_time_ymd = (item) => {
  return item.slice(0, 18);
}

/*
 * 弹框封装
 * success:成功图标
 * wrong:失败图标
 */

const show_toast = (message, type) => {
  let image = null
  switch (parseInt(type)) {
    case 1:
      image = '/resources/toast_success.png'
      break;
    case 2:
      image = '/resources/toast_wrong.png'
      break;
    default:

  }
  if (image == null) {
    wx.showToast({
      icon: "none",
      title: message,
      duration: 1500
    })
  } else {
    wx.showToast({
      title: message,
      image: image,
      duration: 1500
    })
  }

}

const show_model = (title, content, showCancel, confirmText, cancelText) => {
  wx.showModal({
    title: title,
    content: content,
    showCancel: showCancel,
    confirmColor: '#04C900',
    confirmText: confirmText,
    cancelText: cancelText,
    success(res) {
      if (res.confirm) {
        console.log("执行成功");
        return true;
      } else {
        console.log("执行失败");
        return false;
      }
    }
  })
}
//设置导航背景色及文字颜色方法
// backgroundColor：导航背景色
// color：导航文字颜色
const setNavigationStyle = (backgroundColor, color) => {
  wx.setNavigationBarColor({
    frontColor: color,
    backgroundColor: backgroundColor,
    animation: {
      duration: 400,
      timingFunc: 'easeIn'
    }
  })
}

//设置导航文字内容方法
// title：文字内容
const setNavigationTitle = (title) => {
  wx.setNavigationBarTitle({
    title: title
  })
}



module.exports = {
  formatTime: formatTime,
  newRequest: newRequest,
  on,
  emit,
  buttonClickedLong: buttonClickedLong,
  buttonClicked: buttonClicked,
  get_time_ymd: get_time_ymd,
  show_toast: show_toast,
  show_model: show_model,
  setNavigationStyle: setNavigationStyle,
  setNavigationTitle: setNavigationTitle,
}
